package cc.cix.hq.common.core.advice;

import cc.cix.hq.common.core.entity.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cix
 */
@ControllerAdvice
public class BaseResultResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        List<String> list = new ArrayList<>(2);
        list.add("ApiResourceController");
        list.add("Swagger2ControllerWebMvc");

        return !list.contains(methodParameter.getDeclaringClass().getSimpleName());
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (o == null) {
            return Result.success();
        }

        if (o instanceof Result) {
            return o;
        }

        return Result.success(o);
    }
    
}
